#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#define N 10
#define Total 20
sem_t mutex,empty,full;
int buffer[N];
int in=0,out=0;
int produced_count =0;
int consumed_count=0;
void *producer(void *arg)
{
    int item=0;
    while(produced_count<Total)
    {
         item++;
         sem_wait(&empty);
         sem_wait(&mutex);
         buffer[in]=item;
         printf("Producer produced:%d\n",item);
         in=(in+1)%N;
         produced_count++;
         sem_post(&mutex);
         sem_post(&full);
    }
        return NULL;
}
void* consumer(void*arg)
{
        int item;
        while(consumed_count<Total)
         {
                 sem_wait(&full);
                 sem_wait(&mutex);
                 item=buffer[out];
                 printf("Consumer consumed:%d\n",item);
                  out=(out+1)%N;
                 consumed_count++;
                 sem_post(&mutex);
                 sem_post(&empty);
          }
             return NULL;
}
int main()
{
 pthread_t tid_producer,tid_consumer;
 sem_init(&mutex,0,1);
 sem_init(&empty,0,N);
 sem_init(&full,0,0);
pthread_create(&tid_producer,NULL,producer,NULL);
pthread_create(&tid_consumer,NULL,consumer,NULL);
pthread_join(tid_producer,NULL);
pthread_join(tid_consumer,NULL);
sem_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}
